﻿using Jt808CommandEncoder;
using Jt808DataParser;
using Jt808DataParser.Model;
using Jt808DataParser.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Test.Control;
using Test.Model;
using Test.Utils;

namespace Jointech
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            splitContainer1.SplitterDistance = splitContainer1.Width / 2;
            dgv_SetParam.DataSource = listParam;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(richTextBox1.Text))
            {
                richTextBox3.Clear();
                //byte[] byteArr = PacketUtil.decodePacket(Jt808CommandEncoder.Utils.CommonUtil.HexStringToBytes(richTextBox1.Text.Replace(" ", "")));
                byte[] byteArr=Jt808CommandEncoder.Utils.CommonUtil.HexStringToBytes(richTextBox1.Text.Replace(" ", ""));
                List<byte> byteList = Jt808DataParser.Utils.CommonUtil.unescape(byteArr, byteArr.Length);
                string hexStr = Jt808CommandEncoder.Utils.CommonUtil.ByteToHexStr(byteList.ToArray());
                richTextBox3.Text = SplitData(hexStr).ToString();
                string strResult = DataParser.receiveData(richTextBox1.Text);
                if (string.IsNullOrEmpty(strResult))
                {
                    strResult = "Parsing exception, please check whether the data is normal, or contact the developer!";
                }
                richTextBox2.Text = Test.Utils.CommonUtil.ConvertJsonString(strResult);
            }
            else
            {
                MessageBox.Show("Please enter the data to be parsed!", "Tips");
            }
        }

        /// <summary>
        /// Verify the legitimacy of the package
        /// </summary>
        /// <param name="txtContent"></param>
        /// <returns></returns>
        private StringBuilder SplitData(string txtContent)
        {
            txtContent = txtContent.Replace(" ", "");
            StringBuilder sb = new StringBuilder();
            if (txtContent.Length < 30) {
                sb.Append("Insufficient data length!");
                return sb;
            }
            txtContent=txtContent.ToUpper();
            if (txtContent.StartsWith("7E") && txtContent.EndsWith("7E"))
            {
                sb.AppendLine("7E --Flag");
                txtContent = txtContent.Substring(2, txtContent.Length - 2);
                string msgId = txtContent.Substring(0, 4);
                sb.AppendLine(string.Format("{0} --{1}", msgId, "Message ID"));
                txtContent = txtContent.Substring(4, txtContent.Length - 4);

                sb.AppendLine(string.Format("{0} --{1}", txtContent.Substring(0, 4), "Properties of Message Body"));
                txtContent = txtContent.Substring(4, txtContent.Length - 4);

                sb.AppendLine(string.Format("{0} --{1}", txtContent.Substring(0, 12), "Device Number"));
                txtContent = txtContent.Substring(12, txtContent.Length - 12);

                sb.AppendLine(string.Format("{0} --{1}", txtContent.Substring(0, 4), "Message Sequence Number"));
                txtContent = txtContent.Substring(4, txtContent.Length - 4);
                string checkNum = txtContent.Substring(txtContent.Length-4, 2);
                string end = txtContent.Substring(txtContent.Length - 2, 2);

                txtContent = txtContent.Substring(0, txtContent.Length - 4);

                switch (msgId) {
                    case "0200":
                        SplitLocation(sb, txtContent);
                        break;
                    default:
                        sb.Append(string.Format("{0} --{1}", txtContent, "Response message body"));
                        break;
                }
                sb.AppendLine(string.Format("{0} --{1}", checkNum, "Checksum Code"));
                sb.Append(string.Format("{0} --{1}", end, "Flag"));
                return sb;
            }
            else
            {
                sb.Append("Missing package header and tail!");
                return sb;
            }
        }

        private void SplitLocation(StringBuilder sb,string txtContent)
        {
            sb.AppendLine(string.Format("{0} --{1}", txtContent.Substring(0, 8), "Alarm Flag"));
            txtContent = txtContent.Substring(8, txtContent.Length - 8);

            sb.AppendLine(string.Format("{0} --{1}", txtContent.Substring(0, 8), "Status Flag"));
            txtContent = txtContent.Substring(8, txtContent.Length - 8);

            sb.AppendLine(string.Format("{0} --{1}", txtContent.Substring(0, 8), "Latitude"));
            txtContent = txtContent.Substring(8, txtContent.Length - 8);

            sb.AppendLine(string.Format("{0} --{1}", txtContent.Substring(0, 8), "Longitude"));
            txtContent = txtContent.Substring(8, txtContent.Length - 8);

            sb.AppendLine(string.Format("{0} --{1}", txtContent.Substring(0, 4), "Altitude"));
            txtContent = txtContent.Substring(4, txtContent.Length - 4);

            sb.AppendLine(string.Format("{0} --{1}", txtContent.Substring(0, 4), "Speed"));
            txtContent = txtContent.Substring(4, txtContent.Length - 4);

            sb.AppendLine(string.Format("{0} --{1}", txtContent.Substring(0, 4), "Direction"));
            txtContent = txtContent.Substring(4, txtContent.Length - 4);

            sb.AppendLine(string.Format("{0} --{1}", txtContent.Substring(0, 12), "Time"));
            txtContent = txtContent.Substring(12, txtContent.Length - 12);
            SplitLocationExtraInfo(sb, txtContent);
        }

        private void SplitLocationExtraInfo(StringBuilder sb, string txtContent)
        {
            while (txtContent.Length > 3) {
                string extraInfoId = txtContent.Substring(0, 2);
                string extraInfolen = txtContent.Substring(2, 2);
                int bodyLen = Convert.ToInt32(extraInfolen, 16)*2;
                if (bodyLen == 0) {
                    string msg = string.Format("Extension ID:0x{0},Length:{1},Remaining message:{2};The remaining message length is insufficient, which may be abnormal data!",
                        extraInfoId, bodyLen, txtContent);
                    getExtraDesc(sb, extraInfoId, extraInfolen, txtContent.Substring(4, txtContent.Length - 4));
                    MessageBox.Show(msg, "Tips");
                    return;
                }
                if (txtContent.Length - 4 < bodyLen) {
                    string msg = string.Format("Extension ID:0x{0},Length:{1},Remaining message:{2};The remaining message length is insufficient, which may be abnormal data!",
                       extraInfoId, bodyLen, txtContent);
                    getExtraDesc(sb, extraInfoId, extraInfolen, txtContent.Substring(4, txtContent.Length - 4));
                    MessageBox.Show(msg, "Tips");
                    return;
                }
                string extraBody = txtContent.Substring(4, bodyLen);
                getExtraDesc(sb, extraInfoId, extraInfolen, extraBody);
                txtContent = txtContent.Substring(bodyLen+4, txtContent.Length - 4 - bodyLen);
            }
        }

        private string getExtraDesc(StringBuilder sb, string extraInfoId,string extraInfolen,string extraBody) {
            string desc = "Unknow";
            switch (extraInfoId) {
                case "01":
                    desc = "Mileage";
                    sb.AppendLine(string.Format("{0} {1} {2} --{3}", extraInfoId, extraInfolen, extraBody, desc));
                    break;
                case "30":
                    desc = "Mobile Network Signal Strength";
                    sb.AppendLine(string.Format("{0} {1} {2} --{3}", extraInfoId, extraInfolen, extraBody, desc));
                    break;
                case "31":
                    desc = "GNSS Number of Positioning Satellites";
                    sb.AppendLine(string.Format("{0} {1} {2} --{3}", extraInfoId, extraInfolen, extraBody, desc));
                    break;
                case "F0":
                    desc = "Base Station Information";
                    string bodyF0 = extraBody;
                    StringBuilder baseStationAll = new StringBuilder();
                    if (extraBody.Length % 24 == 0)
                    {
                        while (extraBody.Length >= 24)
                        {
                            string bastStation = extraBody.Substring(0, 24);
                            string mcc = bastStation.Substring(0, 4);
                            string mnc = bastStation.Substring(4, 2);
                            string ci = bastStation.Substring(6, 8);
                            string lac = bastStation.Substring(14, 8);
                            string rssi = bastStation.Substring(22, 2);
                            baseStationAll.Append(string.Format("MCC:{0},MNC:{1},CI:{2},LAC:{3},RSSI:{4}", mcc, mnc, ci, lac, rssi));
                            extraBody = extraBody.Substring(24, extraBody.Length - 24);
                        }
                    }
                    else {
                        while (extraBody.Length >= 26)
                        {
                            string bastStation = extraBody.Substring(0, 26);
                            string mcc = bastStation.Substring(0, 4);
                            string mnc = bastStation.Substring(4, 4);
                            string ci = bastStation.Substring(8, 8);
                            string lac = bastStation.Substring(16, 8);
                            string rssi = bastStation.Substring(24, 2);
                            baseStationAll.Append(string.Format("MCC:{0},MNC:{1},CI:{2},LAC:{3},RSSI:{4}", mcc, mnc, ci, lac, rssi));
                            extraBody = extraBody.Substring(26, extraBody.Length - 26);
                        }
                    }
                    sb.AppendLine(string.Format("{0} {1} {2} --{3}", extraInfoId, extraInfolen, bodyF0,string.Format("{0}({1})", desc, baseStationAll.ToString())));
                    break;
                case "F1":
                    desc = "Power Supply (external) Voltage (V Series)";
                    sb.AppendLine(string.Format("{0} {1} {2} --{3}", extraInfoId, extraInfolen, extraBody, desc));
                    break;
                case "F2":
                    desc = "Software Version";
                    sb.AppendLine(string.Format("{0} {1} {2} --{3}", extraInfoId, extraInfolen, extraBody, desc));
                    break;
                case "F3":
                    desc = "Bluetooth List";
                    string bodyF3 = extraBody;
                    StringBuilder bleList = new StringBuilder();
                    string maskBle = extraBody.Substring(0, 2);
                    bleList.Append(maskBle + "(Mask) ");
                    extraBody = extraBody.Substring(2, extraBody.Length - 2);
                    while (extraBody.Length >= 14) {
                        int mask = Convert.ToInt32(maskBle, 16);
                        string mac = extraBody.Substring(0, 12);
                        bleList.Append(mac + "(Mac) ");

                        string rssi = extraBody.Substring(12, 2);
                        bleList.Append(rssi + "(RSSI) ");

                        extraBody = extraBody.Substring(14, extraBody.Length - 14);
                        if ((mask & 0x01) > 0) {
                            string name = extraBody.Substring(0, 20);
                            bleList.Append(name + "(Name) ");
                            extraBody = extraBody.Substring(20, extraBody.Length - 20);
                        }
                        if ((mask & 0x02) > 0)
                        {
                            string FwVer = extraBody.Substring(0, 4);
                            bleList.Append(FwVer + "(FwVer) ");
                            extraBody = extraBody.Substring(4, extraBody.Length - 4);
                        }
                        if ((mask & 0x04) > 0)
                        {
                            string Voltage = extraBody.Substring(0, 4);
                            bleList.Append(Voltage + "(Voltage) ");
                            extraBody = extraBody.Substring(4, extraBody.Length - 4);
                        }

                        if ((mask & 0x08) > 0)
                        {
                            string Temperature = extraBody.Substring(0, 4);
                            bleList.Append(Temperature + "(Temperature) ");
                            extraBody = extraBody.Substring(4, extraBody.Length - 4);
                        }

                        if ((mask & 0x10) > 0)
                        {
                            string Humidity = extraBody.Substring(0, 4);
                            bleList.Append(Humidity + "(Humidity) ");
                            extraBody = extraBody.Substring(4, extraBody.Length - 4);
                        }

                        if ((mask & 0x20) > 0)
                        {
                            string Sensor = extraBody.Substring(0, 12);
                            bleList.Append(Sensor + "(Sensor) ");
                            extraBody = extraBody.Substring(12, extraBody.Length - 12);
                        }
                        if ((mask & 0x40) > 0)
                        {
                            string Res1 = extraBody.Substring(0, 4);
                            bleList.Append(Res1 + "(Res1) ");
                            extraBody = extraBody.Substring(4, extraBody.Length - 4);
                        }
                        if ((mask & 0x80) > 0)
                        {
                            string Res1 = extraBody.Substring(0, 4);
                            bleList.Append(Res1 + "(Res1) ");
                            extraBody = extraBody.Substring(4, extraBody.Length - 4);
                        }
                    }
                    sb.AppendLine(string.Format("{0} {1} {2} --{3}", extraInfoId, extraInfolen, bodyF3, string.Format("{0}({1})", desc, bleList.ToString())));
                    break;
                case "F4":
                    desc = "WIFI List";
                    string bodyF4 = extraBody;
                    StringBuilder wifiList = new StringBuilder();
                    while (extraBody.Length >= 14) {
                        string mac = extraBody.Substring(0, 12);
                        wifiList.Append(mac + "(Mac) ");
                        string rssi = extraBody.Substring(12, 2);
                        wifiList.Append(rssi + "(RSSI) ");
                        extraBody = extraBody.Substring(14, extraBody.Length - 14);
                    }
                    sb.AppendLine(string.Format("{0} {1} {2} --{3}", extraInfoId, extraInfolen, bodyF4, string.Format("{0}({1})", desc, wifiList.ToString())));
                    break;
                case "F5":
                    desc = "GPIO Status(V series)";
                    sb.AppendLine(string.Format("{0} {1} {2} --{3}", extraInfoId, extraInfolen, extraBody, desc));
                    break;
                case "F6":
                    desc = "Trigger Type and Sensors Information";
                    string bodyF6 = extraBody;
                    StringBuilder sensorinfo = new StringBuilder();
                    string dataType = extraBody.Substring(0, 2);
                    string maskF6 = extraBody.Substring(2, 2);
                    extraBody = extraBody.Substring(4, extraBody.Length - 4);
                    sensorinfo.Append(dataType + "(Data type) ");
                    sensorinfo.Append(maskF6 + "(Mask) ");
                    while (extraBody.Length >= 4) {
                        int mask = Convert.ToInt32(maskF6,16);
                        if ((mask & 0x01) > 0) {
                            string Light = extraBody.Substring(0, 4);
                            sensorinfo.Append(Light + "(Light) ");
                            extraBody = extraBody.Substring(4, extraBody.Length - 4);
                        }
                        if ((mask & 0x02) > 0)
                        {
                            string Temperature = extraBody.Substring(0, 4);
                            sensorinfo.Append(Temperature + "(Temperature) ");
                            extraBody = extraBody.Substring(4, extraBody.Length - 4);
                        }
                        if ((mask & 0x04) > 0)
                        {
                            string Humidity = extraBody.Substring(0, 4);
                            sensorinfo.Append(Humidity + "(Humidity) ");
                            extraBody = extraBody.Substring(4, extraBody.Length - 4);
                        }
                        if ((mask & 0x08) > 0)
                        {
                            string Accelerometer = extraBody.Substring(0, 12);
                            sensorinfo.Append(Accelerometer + "(Accelerometer) ");
                            extraBody = extraBody.Substring(12, extraBody.Length - 12);
                        }
                        if ((mask & 0x10) > 0)
                        {
                            string Limit = extraBody.Substring(0, 20);
                            sensorinfo.Append(Limit + "(Limit) ");
                            extraBody = extraBody.Substring(20, extraBody.Length - 20);
                        }
                        if ((mask & 0x20) > 0)
                        {
                            string Res1 = extraBody.Substring(0, 4);
                            sensorinfo.Append(Res1 + "(Res1) ");
                            extraBody = extraBody.Substring(4, extraBody.Length - 4);
                        }
                        if ((mask & 0x40) > 0)
                        {
                            string Res2 = extraBody.Substring(0, 4);
                            sensorinfo.Append(Res2 + "(Res2) ");
                            extraBody = extraBody.Substring(4, extraBody.Length - 4);
                        }
                        if ((mask & 0x80) > 0)
                        {
                            string Res3 = extraBody.Substring(0, 4);
                            sensorinfo.Append(Res3 + "(Res3) ");
                            extraBody = extraBody.Substring(4, extraBody.Length - 4);
                        }
                    }
                    sb.AppendLine(string.Format("{0} {1} {2} --{3}", extraInfoId, extraInfolen, bodyF6, string.Format("{0}({1})", desc, sensorinfo.ToString())));
                    break;
                case "F7":
                    desc = "Battery Information";
                    sb.AppendLine(string.Format("{0} {1} {2} --{3}", extraInfoId, extraInfolen, extraBody, desc));
                    break;
                case "F8":
                    desc = "Device Information(G/A)";
                    sb.AppendLine(string.Format("{0} {1} {2} --{3}", extraInfoId, extraInfolen, extraBody, desc));
                    break;
                case "F9":
                    desc = "Auxiliary Information";
                    sb.AppendLine(string.Format("{0} {1} {2} --{3}", extraInfoId, extraInfolen, extraBody, desc));
                    break;
                case "FA":
                    desc = "Meter Information";
                    sb.AppendLine(string.Format("{0} {1} {2} --{3}", extraInfoId, extraInfolen, extraBody, desc));
                    break;
                default:
                    desc = "Unknow";
                    sb.AppendLine(string.Format("{0} {1} {2} --{3}", extraInfoId, extraInfolen, extraBody, desc));
                    break;
            }
            return desc;
        }

        BindingList<DeviceParameterModel> listParam = new BindingList<DeviceParameterModel>();
        /// <summary>
        /// 0x8013 Setting item selection event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clb_parameterId_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            string selectedText = clb_parameterId.Items[e.Index].ToString();
            string[] selectedTextArr = selectedText.Split('|');
            
            if (e.NewValue == CheckState.Checked)
            {
                DeviceParameterModel otherParamter = Test.Utils.CommonUtil.getDeviceParameterModel(selectedTextArr[0]);

                DeviceParameterModel modelParamter = new DeviceParameterModel();
                modelParamter.parameterID = selectedTextArr[0];
                modelParamter.parameterType = selectedTextArr[1];
                modelParamter.parameterLength = otherParamter.parameterLength;
                modelParamter.parameterUnit = otherParamter.parameterUnit;
                modelParamter.deviceType = otherParamter.deviceType;
                listParam.Add(modelParamter);
            }
            else
            {
                DeviceParameterModel modelParamter = listParam.Where(a => a.parameterID.Equals(selectedTextArr[0])).First();
                listParam.Remove(modelParamter);
            }
        }

        /// <summary>
        /// Encoding command message
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Encoding_Click(object sender, EventArgs e)
        {
            try
            {
                if (tabControl2.SelectedTab.Name.Equals("tab_8103"))
                {
                    if (string.IsNullOrEmpty(txt_deviceId.Text.Trim()))
                    {
                        MessageBox.Show("Please fill in the device ID!", "Tips");
                        return;
                    }
                    if (string.IsNullOrEmpty(txt_msgFlowId.Text.Trim()))
                    {
                        MessageBox.Show("Please fill in the message serial number!", "Tips");
                        return;
                    }
                    if (listParam.Count > 0)
                    {
                        Dictionary<Int32, Object> dicParameters = new Dictionary<int, object>();
                        foreach (DeviceParameterModel item in listParam)
                        {
                            int id = Convert.ToInt32(item.parameterID, 16);
                            object value = item.parameterValue;
                            dicParameters.Add(id, value);
                        }
                        string jsonParam = JsonConvert.SerializeObject(dicParameters);
                        string encodedMessage = CommandEncoder.setDeviceParameterForHex(txt_deviceId.Text.Trim(), int.Parse(txt_msgFlowId.Text.Trim()), dicParameters);
                        if (!string.IsNullOrEmpty(encodedMessage))
                        {
                            txt_EncodedMessage.Text = encodedMessage.ToUpper();
                        }
                        else
                        {
                            MessageBox.Show("Please ensure that the parameters entered are legal!", "Tips");
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show("Please select the item to be configured!", "Tips");
                        return;
                    }
                }
                else if (tabControl2.SelectedTab.Name.Equals("tab_8104"))
                {
                    string encodedMessage = CommandEncoder.queryDeviceParameterForHex(txt_deviceId.Text.Trim(), int.Parse(txt_msgFlowId.Text.Trim()));
                    if (!string.IsNullOrEmpty(encodedMessage))
                    {
                        txt_EncodedMessage.Text = encodedMessage.ToUpper();
                    }
                    else
                    {
                        MessageBox.Show("Please ensure that the parameters entered are legal!", "Tips");
                        return;
                    }
                }
                else if (tabControl2.SelectedTab.Name.Equals("tab_8105"))
                {
                    Dictionary<int, object> dic8105Param = new Dictionary<int, object>();
                    if (clb_8105.CheckedItems.Count > 0)
                    {
                        string[] itemArr = chooseCommandWord.Split('-');
                        switch (int.Parse(itemArr[0]))
                        {
                            case 32:
                                foreach (Control item in this.panel_CommandWord.Controls)
                                {
                                    Command32Word word32 = (Command32Word)item;
                                    Dictionary<string, string> dicWord32Param = new Dictionary<string, string>();
                                    foreach (Control childItem in word32.Controls)
                                    {
                                        if (childItem is Panel)
                                        {
                                            foreach (Control panelItem in childItem.Controls)
                                            {
                                                getWord32Param(panelItem, dicWord32Param);
                                            }
                                        }
                                        else
                                        {
                                            getWord32Param(childItem, dicWord32Param);
                                        }
                                    }
                                    dic8105Param.Add(32, dicWord32Param);
                                }
                                break;
                            case 33:
                                foreach (Control item in this.panel_CommandWord.Controls)
                                {
                                    Command33Word word33 = (Command33Word)item;
                                    foreach (Control childItem in word33.Controls)
                                    {
                                        switch (childItem.Name)
                                        {
                                            case "rdb_connect":
                                                RadioButton rdb_connect = (RadioButton)childItem;
                                                if (rdb_connect.Checked)
                                                {
                                                    dic8105Param.Add(33, 0);
                                                }
                                                else
                                                {
                                                    dic8105Param.Add(33, 1);
                                                }
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                }
                                break;
                            case 34:
                                foreach (Control item in this.panel_CommandWord.Controls)
                                {
                                    Command34Word word34 = (Command34Word)item;
                                    foreach (Control childItem in word34.Controls)
                                    {
                                        switch (childItem.Name)
                                        {
                                            case "rdb_off":
                                                RadioButton rdb_off = (RadioButton)childItem;
                                                if (rdb_off.Checked)
                                                {
                                                    dic8105Param.Add(34, 0);
                                                }
                                                else
                                                {
                                                    dic8105Param.Add(34, 1);
                                                }
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                }
                                break;
                            case 35:
                                foreach (Control item in this.panel_CommandWord.Controls)
                                {
                                    Command35Word word35 = (Command35Word)item;
                                    Dictionary<string, string> dicWord35Param = new Dictionary<string, string>();
                                    foreach (Control childItem in word35.Controls)
                                    {
                                        switch (childItem.Name)
                                        {
                                            case "nud_Channel":
                                                NumericUpDown nud_Channel = (NumericUpDown)childItem;
                                                dicWord35Param.Add("CHANNEL", nud_Channel.Value.ToString());
                                                break;
                                            case "rdb_off":
                                                RadioButton rdb_off = (RadioButton)childItem;
                                                if (rdb_off.Checked)
                                                {
                                                    dicWord35Param.Add("MODE", "0");
                                                }
                                                else
                                                {
                                                    dicWord35Param.Add("MODE", "1");
                                                }
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                    dic8105Param.Add(35, dicWord35Param);
                                }
                                break;
                            case 36:
                                foreach (Control item in this.panel_CommandWord.Controls)
                                {
                                    Command36Word word36 = (Command36Word)item;
                                    foreach (Control childItem in word36.Controls)
                                    {
                                        switch (childItem.Name)
                                        {
                                            case "txt_ATCommand":
                                                TextBox txt_ATCommand = (TextBox)childItem;
                                                if (!string.IsNullOrEmpty(txt_ATCommand.Text.Trim()))
                                                {
                                                    dic8105Param.Add(36, txt_ATCommand.Text.Trim());
                                                }
                                                else
                                                {
                                                    MessageBox.Show("Please entered the AT command", "Tips");
                                                    return;
                                                }
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                }
                                break;
                            default:
                                dic8105Param.Add(int.Parse(itemArr[0]), null);
                                break;
                        }
                    }
                    else
                    {
                        MessageBox.Show("Please check one command word!", "Tips");
                        return;
                    }
                    string jsonParam = JsonConvert.SerializeObject(dic8105Param);
                    string encodedMessage = CommandEncoder.deviceControlCommandForHex(txt_deviceId.Text.Trim(), int.Parse(txt_msgFlowId.Text.Trim()), dic8105Param);
                    if (!string.IsNullOrEmpty(encodedMessage))
                    {
                        txt_EncodedMessage.Text = encodedMessage.ToUpper();
                    }
                    else
                    {
                        MessageBox.Show("Please ensure that the parameters entered are legal!", "Tips");
                        return;
                    }
                }
                else if (tabControl2.SelectedTab.Name.Equals("tab_8900"))
                {
                    Dictionary<int, string> dic8900Param = new Dictionary<int, string>();
                    if (!string.IsNullOrEmpty(rtxt_TransparentData.Text.Trim()))
                    {
                        int transparentType = 0;
                        if (rdb_UART1.Checked)
                        {
                            transparentType = 0x41;
                        }
                        else
                        {
                            transparentType = 0x42;
                        }
                        dic8900Param.Add(transparentType, rtxt_TransparentData.Text.Trim());
                    }
                    else
                    {
                        MessageBox.Show("Please enter the transparent transmission data for hex string", "Tips");
                        return;
                    }
                    string jsonParam = JsonConvert.SerializeObject(dic8900Param);
                    string encodedMessage = CommandEncoder.transparentCommandForHex(txt_deviceId.Text.Trim(), int.Parse(txt_msgFlowId.Text.Trim()), dic8900Param);
                    if (!string.IsNullOrEmpty(encodedMessage))
                    {
                        txt_EncodedMessage.Text = encodedMessage.ToUpper();
                    }
                    else
                    {
                        MessageBox.Show("Please ensure that the parameters entered are legal!", "Tips");
                        return;
                    }
                }
                else if (tabControl2.SelectedTab.Name.Equals("tab_8A00"))
                {
                    Dictionary<int, byte[]> dic8A00Param = new Dictionary<int, byte[]>();
                    if (!string.IsNullOrEmpty(txt_RSA_E.Text.Trim()))
                    {
                        if (!string.IsNullOrEmpty(txt_RSA_N.Text.Trim()))
                        {
                            dic8A00Param.Add(int.Parse(txt_RSA_E.Text.Trim()), Jt808CommandEncoder.Utils.CommonUtil.HexStringToBytes(txt_RSA_N.Text.Trim()));
                        }
                        else
                        {
                            MessageBox.Show("Please enter the N in RSA public key {e, n}(byte[128]) for hex string", "Tips");
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show("Please enter the E in platform RSA public key {e, n}(4 byte)", "Tips");
                        return;
                    }
                    string encodedMessage = CommandEncoder.platformRSAPublicKeyCommandForHex(txt_deviceId.Text.Trim(), int.Parse(txt_msgFlowId.Text.Trim()), dic8A00Param);
                    if (!string.IsNullOrEmpty(encodedMessage))
                    {
                        txt_EncodedMessage.Text = encodedMessage.ToUpper();
                    }
                    else
                    {
                        MessageBox.Show("Please ensure that the parameters entered are legal!", "Tips");
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Please ensure that the parameters entered are legal!","Tips");
            }
        }

        string chooseCommandWord = string.Empty;
        /// <summary>
        /// check a item
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clb_8105_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (clb_8105.CheckedItems.Count > 0)
            {
                for (int i = 0; i < clb_8105.Items.Count; i++) 
                {
                    if (i != e.Index)
                    {
                        clb_8105.SetItemCheckState(i, CheckState.Unchecked);
                    }
                }
            }
            chooseCommandWord = clb_8105.Items[e.Index].ToString();
            string[] itemArr = chooseCommandWord.Split('-');
            lab_ForDeviceType.Text = Test.Utils.CommonUtil.getCommandWordForDevice(int.Parse(itemArr[0]));
            //show paramters when choose one command word
            AddCommandWordParamterControl(int.Parse(itemArr[0]));
        }

        /// <summary>
        /// Display different parameter panels according to different command word
        /// </summary>
        /// <param name="word"></param>
        private void AddCommandWordParamterControl(int word)
        {
            if (this.panel_CommandWord.Controls.Count > 0)
            {
                this.panel_CommandWord.Controls.Clear();
            }
            switch (word)
            {
                case 32:
                    Command32Word word32 = new Command32Word();
                    this.panel_CommandWord.Controls.Add(word32);
                    break;
                case 33:
                    Command33Word word33 = new Command33Word();
                    this.panel_CommandWord.Controls.Add(word33);
                    break;
                case 34:
                    Command34Word word34 = new Command34Word();
                    this.panel_CommandWord.Controls.Add(word34);
                    break;
                case 35:
                    Command35Word word35 = new Command35Word();
                    this.panel_CommandWord.Controls.Add(word35);
                    break;
                case 36:
                    Command36Word word36 = new Command36Word();
                    this.panel_CommandWord.Controls.Add(word36);
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// foreach this father controls,get 32 command word parameters
        /// </summary>
        /// <param name="childItem"></param>
        /// <param name="dicWord32Param"></param>
        private void getWord32Param(Control childItem, Dictionary<string,string> dicWord32Param)
        {
            switch (childItem.Name)
            {
                case "rdb_App":
                    RadioButton rdb_App = (RadioButton)childItem;
                    if (rdb_App.Checked)
                    {
                        dicWord32Param.Add("TYPE", "0");
                    }
                    else
                    {
                        dicWord32Param.Add("TYPE", "1");
                    }
                    break;
                case "rdb_Full":
                    RadioButton rdb_Full = (RadioButton)childItem;
                    if (rdb_Full.Checked)
                    {
                        dicWord32Param.Add("MODE", "0");
                    }
                    else
                    {
                        dicWord32Param.Add("MODE", "1");
                    }
                    break;
                case "rdb_FTP":
                    RadioButton rdb_FTP = (RadioButton)childItem;
                    if (rdb_FTP.Checked)
                    {
                        dicWord32Param.Add("PROTOCOL", "0");
                    }
                    else
                    {
                        dicWord32Param.Add("PROTOCOL", "1");
                    }
                    break;
                case "txt_Version":
                    TextBox txt_Version = (TextBox)childItem;
                    if (!string.IsNullOrEmpty(txt_Version.Text.Trim()))
                    {
                        dicWord32Param.Add("VERSION", txt_Version.Text.Trim());
                    }
                    else
                    {
                        MessageBox.Show("Please insert version text!","Tips");
                        return;
                    }
                    break;
                case "txt_URL":
                    TextBox txt_URL = (TextBox)childItem;
                    if (!string.IsNullOrEmpty(txt_URL.Text.Trim()))
                    {
                        dicWord32Param.Add("URL", txt_URL.Text.Trim());
                    }
                    else
                    {
                        MessageBox.Show("Please insert URL text!","Tips");
                        return;
                    }
                    break;
                case "txt_MD5":
                    TextBox txt_MD5 = (TextBox)childItem;
                    if (!string.IsNullOrEmpty(txt_MD5.Text.Trim()))
                    {
                        dicWord32Param.Add("MD5", txt_MD5.Text.Trim());
                    }
                    break;
                default:
                    break;
            }
        }

        private void richTextBox3_TextChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < richTextBox3.Lines.Length; i++)
            {
                string[] lineArr = richTextBox3.Lines[i].Split(new string[] { " --" }, StringSplitOptions.None);
                if (lineArr.Count() > 1)
                {
                    int lineFirstCharIndex = richTextBox3.GetFirstCharIndexFromLine(i);
                    richTextBox3.Select(lineFirstCharIndex, lineArr[0].Length);
                    if (lineArr[1].Equals("Unknow"))
                    {
                        richTextBox3.SelectionColor = Color.Red;
                    }
                    else
                    {
                        richTextBox3.SelectionColor = Color.Green;
                    }
                }
                //对选中的字体进行加粗处理
                richTextBox3.SelectionFont = new Font(richTextBox3.Font.FontFamily, richTextBox3.Font.Size, FontStyle.Bold);
            }
        }
    }
}
